/*
 * @Author: hukai huzhengen@gmail.com
 * @Date: 2024-04-07 16:07:52
 * @LastEditors: hukai huzhengen@gmail.com
 * @LastEditTime: 2025-09-12 17:30:17
 * @FilePath: \pls\src\utils\websocket.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { time } from 'echarts'
import store from '../store'

let webSocket = null
let socketOpen = false

function generateRandom3Digit() {
    return Math.floor(Math.random() * 900) + 100;
}
// 发送消息
// 初始化websocket
export const contactSocket = val => {
    console.log(val)
    if ('WebSocket' in window) {
        // webSocket = new WebSocket("wss://www.jibantong.com/websocket/message/" + val);
        // webSocket = new WebSocket('ws://www.jibantong.com/websocket/message/' + val)
        // webSocket = new WebSocket('ws://1.92.87.133:8081/websocket/message/' + val) //测试
        webSocket = new WebSocket('ws://192.168.1.12:8020/websocket/message/' + generateRandom3Digit())
        webSocket.onopen = function () {
            console.log('连接成功！')
        }
        webSocket.onmessage = function (evt) {
            if (evt.data == '连接成功') return
            var json2 = '(' + evt.data + ')' //第二种
            console.log(json2)
            // 1. 创建时间字符串
            const now = new Date();
            const timeStr = [
                now.getFullYear(),
                String(now.getMonth() + 1).padStart(2, '0'),
                String(now.getDate()).padStart(2, '0')
            ].join('-') + ' ' + [
                String(now.getHours()).padStart(2, '0'),
                String(now.getMinutes()).padStart(2, '0'),
                String(now.getSeconds()).padStart(2, '0')
            ].join(':');

            // 2. 打印
            console.log('收到消息时间：', JSON.parse(evt.data));
            const T = JSON.parse(evt.data);
            store.commit('MON_ITOR', { ...T, time: timeStr })
        }
        webSocket.onclose = function () {
            console.log('连接关闭！')
        }
        webSocket.onerror = function () {
            console.log('连接异常！')
        }
    }
}
